const moment = require("moment");
const fs = require('fs');
const path = require('path');
const _ = require('lodash');

const getSize = require('get-folder-size');
const prefix = '/api/system';
module.exports = (app) => {
    const {router, middleware} = app;

    /**系统状态*/
    router.get(prefix, middleware.api(2), async ctx => {
        const res = {};
        res.screenshot = Object.keys(app.io.sockets.sockets).length;
        let [users, anchors, projects, files, filesSize, events] = await Promise.all([
            app.model.User.count(),
            app.model.DetailAnchor.count(),
            app.model.Project.count(),
            // app.model.File.count(),
            folderFiles(app.config.screenshot.path),
            folderSize(app.config.screenshot.path),
            app.model.Event.count(),
        ]);
        res.users = users;
        res.anchors = anchors;
        res.projects = projects;
        res.files = files;
        res.filesSize = filesSize;
        res.events = events;
        let clients = await app.redis.keys(app.config.screenshot.redisClientKey + '*');
        if (clients.length > 0) {
            clients = await app.redis.mget(...clients);
            res.screenshotClients = _.map(clients, client => {
                let c = JSON.parse(client);
                let seconds = Math.floor((Date.now() - c.started_at) / 1000);
                let day = Math.floor(seconds / (24 * 3600));
                let hour = Math.floor(seconds / 3600) % 24;
                let min = Math.floor(seconds / 60) % 60;
                let sec = seconds % 60;
                c.started_at = '';
                if (day > 0)
                    c.started_at += day + '天';
                if (hour > 0)
                    c.started_at += hour + '小时';
                if (min > 0)
                    c.started_at += min + '分';
                if (sec > 0)
                    c.started_at += sec + '秒';
                return c;
            });
        }
        ctx.body = res;
    });

    const count = async (ctx, next) => {
        let {date, all} = ctx.query;
        if (_.isEmpty(date))
            return ctx.helper.error('缺少日期数据');
        all = all === '1';
        date = moment(date).startOf('day');
        let where = {selected: false, created_at: {[app.Sequelize.Op.lt]: date.toDate()}};
        if (all)
            delete where.selected;
        ctx.where = where;
        ctx.date = date.format('YYYY-MM-DD');
        await next();
    };

    /**统计将会删除的文件数量*/
    router.get(prefix + '/clear_file_count', count, async ctx => {
        let count = await app.model.File.count({where: ctx.where});
        ctx.body = '预计将会删除 ' + count + ' 个文件';
    });

    /**删除文件*/
    router.get(prefix + '/clear_file', middleware.api(2), count, async ctx => {

        await app.model.File.update({deleted: true}, {where: ctx.where});

        let all = ctx.query.all === '1' ? '全部' : '未使用的';
        let message = `已经将 ${ctx.date} 之前的 ${all} 文件 标记为删除`;
        ctx.service.event.add(message);
        ctx.body = message;
    });

    /**重启截图程序*/
    router.get(prefix + '/restart-client/:id', async ctx => {
        let socket = app.io.sockets.sockets[ctx.params.id];
        if (!socket)
            return ctx.helper.error('无法找到对应的截图程序');
        socket.emit('restart', '');
        ctx.body = '已经发送重启命令';
    });
};

/**
 * 文件数量
 * @param path
 * @returns {Promise<any>}
 */
function folderFiles(path) {
    return new Promise(resolve => {
        fs.readdir(path, (err, files) => {
            //过滤一些.开头的文件
            files = files.filter(file => file.indexOf('.') !== 0);
            resolve(files.length);
        });
    });
}

/**
 * 文件夹的大小
 * @param path
 * @returns {Promise<any>}
 */
function folderSize(path) {
    return new Promise(resolve => {
        getSize(path, (err, size) => {
            resolve((size / 1024 / 1024).toFixed(2) + ' MB');
        });
    });
}